package com.pengzy.core;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.pengzy.comment.mybatis.entity.SysUser;
import com.pengzy.comment.mybatis.mapper.SysMenuMapper;
import com.pengzy.comment.mybatis.mapper.SysUserMapper;
import com.pengzy.comment.web.exception.CustomException;
import com.pengzy.supports.dto.LoginUser;
import com.pengzy.supports.dto.UserDetail;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * 重写security的UserDetailsService接口，用来与数据库交互，查询用户信息
 * @author xiaozhi
 */
@Service
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private SysMenuMapper sysMenuMapper;

    @Override
    public UserDetails loadUserByUsername(String username) {
        //根据用户名查询用户信息
        SysUser user=getUser(username);
        UserDetail detail= BeanUtil.toBean(user, UserDetail.class);
        //TODO 根据用户查询权限信息 添加到LoginUser中
        List<String> list=sysMenuMapper.menuList(user.getUserId());
        //封装成UserDetails对象返回
        return new LoginUser(detail,list,detail.getUserName(),detail.getPassword());
    }


    public SysUser getUser(String username){
        LambdaQueryWrapper<SysUser> userLambdaQueryWrapper= Wrappers.lambdaQuery();
        userLambdaQueryWrapper.eq(SysUser::getUserName,username)
                .last("limit 1");
        SysUser sysUser = sysUserMapper.selectOne(userLambdaQueryWrapper);
        if(Objects.isNull(sysUser)){
            throw new CustomException("用户或者密码为错误！");
        }
        return sysUser;
    }
}
